from django.db import models
from django.db.models import QuerySet

from users.models import User


class NotDeletedManager(models.Manager.from_queryset(QuerySet)):
    def get_queryset(self, ignore_deleted=False):
        if ignore_deleted:
            return super().get_queryset()

        return super(NotDeletedManager, self).get_queryset().filter(is_delete=False).order_by(
            "-update_time")


class BaseModel(models.Model):
    """公共字段模型"""
    name = models.CharField(max_length=100, verbose_name='名称/标题', null=True, blank=True)
    orders = models.IntegerField(verbose_name='显示顺序', null=True, blank=True)
    is_delete = models.BooleanField(verbose_name="逻辑删除", default=False)
    create_time = models.DateTimeField(auto_now_add=True, verbose_name="添加时间")
    update_time = models.DateTimeField(auto_now=True, verbose_name="更新时间")
    create_by = models.ForeignKey(User, on_delete=models.CASCADE, default=1, verbose_name='创建人', related_name='+')
    modified_by = models.ForeignKey(User, on_delete=models.CASCADE, default=1, verbose_name='修改人', related_name='+')
    advanced_objects = NotDeletedManager()
    objects = QuerySet.as_manager()

    class Meta:
        # 设置当前模型在数据迁移的时候不要为它创建表
        abstract = True

    def __str__(self):
        return f'<{self.__class__.__name__} {self.name}>'
